//
//  LYTabBar.m
//  lottery
//
//  Created by 赵国腾 on 16/6/10.
//  Copyright © 2016年 赵国腾. All rights reserved.
//

#import "LYTabBar.h"
#import "LYTabBarButton.h"

@interface LYTabBar ()

/** 当前选中的按钮 */
@property (nonatomic, strong) UIButton *curSelectedButton;

@end

@implementation LYTabBar


- (void)setup {
    
    
}

- (void)setItems:(NSArray *)items {
    
    _items = items;
    
    for (UITabBarItem *item in items) {
        
        LYTabBarButton *button = [LYTabBarButton buttonWithType:UIButtonTypeCustom];
        
        button.tag = self.subviews.count;
        [button setBackgroundImage:item.image forState:UIControlStateNormal];
        [button setBackgroundImage:item.selectedImage forState:UIControlStateSelected];
        
        [button addTarget:self action:@selector(buttonTouchDown:) forControlEvents:UIControlEventTouchDown];
        [self addSubview:button];
        
        if (self.subviews.count == 1) {
            [self buttonTouchDown:button];
        }
        
    }
}

- (void)buttonTouchDown:(UIButton *)sender {
    
    self.curSelectedButton.selected = NO;
    
    sender.selected = YES;
    
    self.curSelectedButton = sender;
    
    // 通知控制器切换页面
    if ([self.delegate respondsToSelector:@selector(tabBar:didClickIndex:)]) {
        [self.delegate tabBar:self didClickIndex:sender.tag];
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    NSInteger count = self.items.count;
    
    CGFloat x = 0;
    CGFloat y = 0;
    CGFloat w = self.bounds.size.width / count;
    CGFloat h = self.bounds.size.height;

    for (NSInteger i = 0; i < count; i++) {
        
        UIButton *button = self.subviews[i];
        
        x = w * i;
        button.frame = CGRectMake(x, y, w, h);
    }
    
}


@end
















